//时间格式转换为时间戳
function js_strto_time(time) {
    var new_str = time.replace(/:/g, '-');
    new_str = new_str.replace(/ /g, '-');
    new_str = new_str.replace(/\//g, '-');
    var arr = new_str.split("-");
    var datum = new Date(Date.UTC(arr[0], arr[1] - 1, arr[2], arr[3] - 8, arr[4], arr[5]));
    return strtotime = datum.getTime() / 1000;
}
//时间戳数据转换为时间格式
function js_date_time(unixtime) {
    var timestr = new Date(parseInt(unixtime)*1000);
    var year= timestr.getFullYear(); 
    var month= timestr.getMonth()+1; 
    var date= timestr.getDate(); 
    var hour= timestr.getHours(); 
    var minute= timestr.getMinutes(); 
    var second= timestr.getSeconds(); 
    var datetime = year+"/"+month+"/"+date+" "+hour+":"+minute+":"+second; 
    return datetime;
}

//获取url参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}

//返回上一级
function previous() {
    window.location = "../policyList.html?type=" + type + "&id=" + DepotID + "&name=" + base64.encode(DepotName) + "";
}

var base64 = new Base64();
var type = getQueryString("type");
var DepotID = getQueryString("DepotID");
var DepotName = getQueryString("DepotName");
DepotName = base64.decode(DepotName);


var webCategory = {};
var PolicyObj = {
    "CWebTypes": {
        "CWebType": []
    },
    "C_TimeSlots": {
        "C_TimeSlot": []
    },
    "MessageSerialNo": "111"
};

function generateParameter() {
    var o = {
        CType: $("#CType").val(),
        CWebTypes: PolicyObj.CWebTypes,
        C_TimeSlots: PolicyObj.C_TimeSlots,
        Adv_URL: $("#Adv_URL").val(),
        MessageSerialNo: PolicyObj.MessageSerialNo
    }
    return o;
}
function save() {
    var form = $(".main-container .form-horizontal").validate();
    if (!form.form()) {
        return;
    }

    var comment = $(".policy_desc").val();
    var policy = generateParameter();
    policy = JSON.stringify(policy);

    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/create.do",
        data: {comment: comment, policy: policy, type: type, instance: DepotName},
        dataType: "json",
        success: function(data) {
            if (data.result == "true") {
                alert("添加成功！");
                previous();
            } else {
                alert("添加失败!")
            }
        }
    });
}

function edit() {
    var form = $(".main-container .form-horizontal").validate();
    if (!form.form()) {
        return;
    }

    var comment = $(".policy_desc").val();
    var policy = generateParameter();
    policy = JSON.stringify(policy);

    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/update.do",
        data: {messageNo: id, comment: comment, policy: policy, type: type, instance: DepotName},
        dataType: "json",
        success: function(data) {
            if (data.result == "true") {
                alert("修改成功！");
                previous();
            } else {
                alert("修改失败!")
            }
        }
    });
}

function showData(resp) {
    var messageType = resp.MessageType;
    var messageNo = resp.MessageNo;
    var instanceName = resp.Instance;
    var comment = resp.Comment;
    PolicyObj = resp.Content;

    $(".policy_desc").val(comment);
    $("#Adv_URL").val(PolicyObj.Adv_URL);
    $("#CType").val(PolicyObj.CType);
    $("#CType").trigger('change');

    refreshWebType();
    refreshTimeSeg();
}

// 添加Web类别
function addWebBox() {
    var cont = '';
    cont += "<div class='modal fade' id='myModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>";
    cont += "            <div class='modal-dialog'>";
    cont += "                <div class='modal-content'>";
    cont += "                    <div class='modal-header'>";
    cont += "                        <button type='button' class='close' data-dismiss='modal'><span aria-hidden='true'>&times;</span></button>";
    cont += "                        <h4 class='modal-title' id='myModalLabel'>添加Web类别</h4>";
    cont += "                    </div>";
    cont += "                    <div class='modal-body'>";
    cont += "                        <form class='form-horizontal'>";
    cont += "                            <div class=' row-fluid'>";
    cont += "                                <div class='control-group'>";
    cont += "                                    <label class='control-label' for='IPType'>Web类别：</label>";
    cont += "                                    <div class='controls'>";
    cont += "                                        <select id='IPType' class='IPType'>";
    for (var i in webCategory) {
        cont += "<option value='" + i + "'>" + webCategory[i] + "</option>";
    }
    cont += "                                        </select>";
    cont += "                                    </div>";
    cont += "                                </div>";
    cont += "                            </div>";
    cont += "                        </form>";
    cont += "                    </div>";
    cont += "                    <div class='modal-footer'>";
    cont += "                        <a href='javascript:void(0)' class='btn btn-default' onclick='closeBox()'>取消</a>";
    cont += "                        <a href='javascript:void(0)' class='btn btn-primary' onclick='addWebCategory()'>确定</a>";
    cont += "                    </div>";
    cont += "                </div>";
    cont += "            </div>";
    cont += "        </div>";
    $("body").append(cont);
    $("#myModal").modal("show");
}

function closeBox() {
    $("#myModal").modal('hide')
    $("#myModal").remove();
}

function refreshWebType() {
    var obj = $(".CWebTypes tbody");
    var cont = "";
    var number = 0;
    var webTypes = PolicyObj.CWebTypes.CWebType;
    for (var i in webTypes) {
        cont += "<tr>";
        cont += "<td>" + webCategory[webTypes[i]] + "</td>";
        cont += "<td><a href='javascript:delWebType(" + number + ")'>&nbsp;删&nbsp;除&nbsp;</a></td>";
        cont += "</tr>";
        number++;
    }
    obj.html("");
    obj.append(cont);
}

function delWebType(index) {
    PolicyObj.CWebTypes.CWebType.splice(index, 1);
    refreshWebType();
}

function addWebCategory() {
    PolicyObj.CWebTypes.CWebType.push($("#IPType").val());
    refreshWebType();
    closeBox();
}

// 添加时间段
function addTimeSegBox() {
    var cont = '';
    cont += "<div class='modal fade' id='myModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>";
    cont += "            <div class='modal-dialog'>";
    cont += "                <div class='modal-content'>";
    cont += "                    <div class='modal-header'>";
    cont += "                        <button type='button' class='close' data-dismiss='modal'><span aria-hidden='true'>&times;</span></button>";
    cont += "                        <h4 class='modal-title' id='myModalLabel'>添加时间段</h4>";
    cont += "                    </div>";
    cont += "                    <div class='modal-body'>";
    cont += "                        <form class='form-horizontal'>";
    cont += "                            <div class=' row-fluid'>";
    cont += "                                <div class='control-group'>";
    cont += "                                    <label class='control-label' for='CStartTime'>起始时间：</label>";
    cont += "                                    <div class='controls'>";
    cont += "                                        <input type='text' id='CStartTime' name='CStartTime' class='CStartTime ip' required/>";
    cont += "                                    </div>";
    cont += "                                </div>";
    cont += "                                <div class='control-group'>";
    cont += "                                    <label class='control-label' for='CEndTime'>结束时间：</label>";
    cont += "                                    <div class='controls'>";
    cont += "                                        <input type='text' id='CEndTime' name='CEndTime' class='CEndTime number' required/>";
    cont += "                                    </div>";
    cont += "                                </div>";
    cont += "                            </div>";
    cont += "                        </form>";
    cont += "                    </div>";
    cont += "                    <div class='modal-footer'>";
    cont += "                        <a href='javascript:void(0)' class='btn btn-default' onclick='closeBox()'>取消</a>";
    cont += "                        <a href='javascript:void(0)' class='btn btn-primary' onclick='addTimeSegment()'>确定</a>";
    cont += "                    </div>";
    cont += "                </div>";
    cont += "            </div>";
    cont += "        </div>";
    $("body").append(cont);
    //时间插件
    var start = {
        elem: '#CStartTime',
        format: 'YYYY/MM/DD hh:mm:ss',
        istime: true,
        istoday: false,
        festival: true,
        choose: function(datas) {
            end.min = datas; //开始日选好后，重置结束日的最小日期
            end.start = datas //将结束日的初始值设定为开始日
        }
    };
    var end = {
        elem: '#CEndTime',
        format: 'YYYY/MM/DD hh:mm:ss',
        istime: true,
        istoday: false,
        festival: true,
        choose: function(datas) {
            start.max = datas; //结束日选好后，重置开始日的最大日期
        }
    };
    laydate(start);
    laydate(end);
    $("#myModal").modal('show');
}

function refreshTimeSeg() {
    var obj = $(".C_TimeSlots tbody");
    var cont = "";
    var number = 0;
    var webTypes = PolicyObj.C_TimeSlots.C_TimeSlot;
    for (var i in webTypes) {
        cont += "<tr>";
        cont += "<td>" + js_date_time(webTypes[i].C_Starttime * 1) + "</td>";
        cont += "<td>" + js_date_time(webTypes[i].C_Stoptime * 1) + "</td>";
        cont += "<td><a href='javascript:delTimeSeg(" + number + ")'>&nbsp;删&nbsp;除&nbsp;</a></td>";
        cont += "</tr>";
        number++;
    }
    obj.html("");
    obj.append(cont);
}

function delTimeSeg(num) {
    PolicyObj.C_TimeSlots.C_TimeSlot.splice(num, 1);
    refreshTimeSeg();
}

function addTimeSegment() {
    var startTime = js_strto_time($("#CStartTime").val());
//    startTime = js_strto_time(startTime) + "";
    var endTime = js_strto_time($("#CEndTime").val());
//    endTime = js_strto_time(endTime) + "";
    PolicyObj.C_TimeSlots.C_TimeSlot.push({
        "C_Starttime": startTime,
        "C_Stoptime": endTime
    })
    refreshTimeSeg();
    closeBox();
}

$(function() {
    $(".Adv_URL").closest(".control-group").hide();
    $(".CType").on('change', function() {
        if (parseInt($(this).val()) == 3) {
            $(".Adv_URL").closest(".control-group").show();
        } else {
            $(".Adv_URL").closest(".control-group").hide();
        }
    });

    $.ajax({
        method: "POST",
        async: false,
        url: "../../assets/data/WebCategory.json",
        dataType: 'json',
        success: function(resp) {
            for (var i in resp) {
                var index = parseInt(i);
                webCategory[index] = resp[i];
            }
        }
    });

//    setInterval(function () {
//        parent.$("#page-content").attr("height", $("html").height());
//    }, 500);
});
/*
 * 查看旧版本的策略内容
 */
function show_oldPolicy(array, number) {
    var souData = array[number];
    $(".header").text("当前策略在" + souData.CreateTime + "创建,ID为" + souData.MessageNo + ",版本号为" + souData.MessageSerialNo + ",属于" + souData.Instance + "策略库");

    showData(souData);
}

/*
 *获取所有版本的策略内容 
 */
function getAllPolicy() {
    $.ajax({
        type: "GET",
        async: false,
        url: "../../action/policy/history_policy_info.do",
        data: {type: type, instance: getQueryString("DepotName"), messageNo: id},
        dataType: "json",
        success: function(data) {
            policyArray = data;
            policyAmount = data.length
        }
    });
}